package com.reverse;

public class ReverseLinkedList1 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(4);
        ListNode tail = new ListNode(5);

        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = tail;
        tail.next = null;

        ListNode head2 = head;
        while (head2 != null) {
            System.out.print(head2.val);
            head2 = head2.next;
            if (head2 != null) {
                System.out.print("->");
            }
        }
        System.out.println();
        head2 = reverse2(head);
        while (head2 != null) {
            System.out.print(head2.val);
            head2 = head2.next;
            if (head2 != null) {
                System.out.print("->");
            }
        }
    }

    public static ListNode reverseLinkedList(ListNode head) {
        if (head == null) return head;

        ListNode prev = head;
        ListNode current = head.next;

        prev.next = null;
        while (current != null) {//不是最后一个节点 一直循环后移
            ListNode next = current.next;
            current.next = prev;
            prev = current;
            current = next;
        }
        return prev;
    }

    public static ListNode reverse2(ListNode head) {
        if (head == null) return head;

        ListNode prev = head;
        ListNode current = head.next;

        prev.next = null;
        while (current != null) {
            ListNode next = current.next;

            current.next = prev;

            prev = current;
            current = next;
        }

        return prev;
    }
}
